﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using NovoGenus.Sockets.Http.Headers;
using System.Collections;

namespace NovoGenus.Sockets.Http
{
    public class HttpResponse
    {
        public HttpResponseHeaders Headers { get; set; }

        public string Body { get; set; }


        public HttpResponse()
        {
            Headers = new HttpResponseHeaders();
            Body = string.Empty;
        }

        public void ParseBodyResponse(ref byte[] bodyBytes, int hEol, int dataLength)
        {
            if (Headers.TransferEncoding != null && Headers.TransferEncoding.ToLower().Equals("chunked"))
            {
                //find the seperator
                Body = Encoding.UTF8.GetString(bodyBytes, hEol, dataLength - hEol);
            }
            else
            {
                Body = Encoding.UTF8.GetString(bodyBytes, hEol, dataLength - hEol);
            }
        }

        public int ParseBodyChunkedResponse(ref byte[] data, ref int indexStart, ref int dataLength)
        {
            int readAheadLimit = 512;
            int chunkedLength = 0;
            bool hexFound = false;
            int length = dataLength > indexStart ? dataLength - indexStart : dataLength;
            string body = Encoding.UTF8.GetString(data, indexStart, length);
            char[] sepearator = new char[] { '\r', '\n' };
            string[] findHex = body.Split(sepearator,StringSplitOptions.RemoveEmptyEntries);
            for(int i=0;i<findHex.Length;i++)
            {
                if (!hexFound && Int32.TryParse(findHex[i], System.Globalization.NumberStyles.AllowHexSpecifier, null, out chunkedLength))
                {
                    hexFound = true;                   
                }
                else
                {
                    Body += string.Concat(findHex[i], "\r\n");
                }
            }

            return hexFound ? chunkedLength : readAheadLimit;
        }


    }
}
